package com.hinnotek.amoeba.ui.activity.old

import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import com.lee.common.base.BaseActivity
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.adapters.old.MsgHistoryBean
import com.hinnotek.amoeba.adapters.old.MsgHistoryListAdapter
import com.hinnotek.amoeba.bean.old.*
import com.hinnotek.amoeba.databinding.IncludeRecyclerviewRefreshBinding
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.ext.init
import com.hinnotek.amoeba.utilities.IntentUtils
import com.hinnotek.amoeba.utilities.ToastUtils
import com.hinnotek.amoeba.viewmodels.NoticeViewModel
import com.lee.common.network.net.ObserverState
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.chad.library.adapter.base.BaseQuickAdapter as BaseQuickAdapter1


class MsgHistoryListActivity : BaseActivity<IncludeRecyclerviewRefreshBinding>() {

    private val viewModel by viewModels<NoticeViewModel>()
    private lateinit var mAdapter: MsgHistoryListAdapter
    private var pageNo = 1
    private val pageSize = 20

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setLeftVisible(true)
        setTitle("记录")

        setContentView(R.layout.include_recyclerview_refresh)
    }

    override fun initVew() {
        bindingView.recyclerView.init()
        bindingView.recyclerView.adapter = MsgHistoryListAdapter().also { mAdapter = it }
    }

    override fun setData() {
        val msgType = intent.getIntExtra("msgType", 0)
        val applyUserId = intent.getIntExtra("applyUserId", 0)
        val approvalUserId = intent.getStringExtra("approvalUserId")
        mAdapter.setOnItemClickListener { adapter: BaseQuickAdapter1<*, *>, _: View?, position: Int ->
            val msgBean = adapter.getItem(position) as MsgHistoryBean
            val bundle = Bundle()
            when (msgType) {
                1 -> {
                    bundle.putInt("amibaInstallId", msgBean.Id)
                    IntentUtils.startActivity(
                        this,
                        TIOtherinsViewingDetailActivity::class.java, bundle
                    )
                }
                2 -> {
                    bundle.putInt("amibaPayId", msgBean.Id)
                    IntentUtils.startActivity(
                        this,
                        PaymentRequestDetailAmoebaActivity::class.java, bundle
                    )
                }
                3 -> {
                    bundle.putInt("amibaPurchaseId", msgBean.Id)
                    bundle.putBoolean("is_msg", true)
                    when (msgBean.applyUserType) {
                        "1" -> {
                            bundle.putString("purchase_type_to", "market")
                        }
                        "2" -> {
                            bundle.putString("purchase_type_to", "technology")
                        }
                        "3" -> {
                            bundle.putString("purchase_type_to", "rD")
                        }
                    }
                    IntentUtils.startActivity(
                        this, SellPurchaseRequisitionDetailActivity::class.java, bundle
                    )
                }
                4 -> {
                    bundle.putInt("amibaReimburseId", msgBean.Id)
                    bundle.putBoolean("is_msg", true)
                    IntentUtils.startActivity(this, WipeOutDetailActivity::class.java, bundle)
                }
                5 -> {
                    bundle.putInt("amibaTemporaryId", msgBean.Id)
                    IntentUtils.startActivity(
                        this, RenewalPaymentDetailActivity::class.java, bundle)
                }
                6 -> {
                    bundle.putInt("companyPurchaseId", msgBean.Id)
                    IntentUtils.startActivity(this, PurchaseDetailActivity::class.java, bundle)
                }
                7 -> {
                    bundle.putInt("companyPhonePayId", msgBean.Id)
                    IntentUtils.startActivity(
                        this, PhoneNumberPaymentDetailActivity::class.java, bundle)
                }
            }
        }

        //下拉刷新
        bindingView.refreshLayout.setOnRefreshListener { refreshLayout: RefreshLayout ->
            refreshLayout.layout.postDelayed(
                {
                    pageNo = 1
                    when (msgType) {
                        1 -> getAmibaInstallPageForHistory(applyUserId, approvalUserId)
                        2 -> getAmibaPayPageForHistory(applyUserId, approvalUserId)
                        3 -> getAmibaPurchasePageForHistory(applyUserId, approvalUserId)
                        4 -> getAmibaReimbursePageForHistory(applyUserId, approvalUserId)
                        5 -> getAmibaTemporaryePageForHistory(applyUserId, approvalUserId)
                        6 -> getCompanyPurchasePageForHistory(applyUserId, approvalUserId)
                        7 -> getCompanyPhonePayPageForHistory(applyUserId, approvalUserId)
                    }
                    refreshLayout.finishRefresh()
                }, 0
            )
        }
        //上拉加载
        bindingView.refreshLayout.setOnLoadMoreListener { refreshLayout: RefreshLayout ->
            refreshLayout.layout.postDelayed(
                {
                    pageNo++
                    when (msgType) {
                        1 -> getAmibaInstallPageForHistory(applyUserId, approvalUserId)
                        2 -> getAmibaPayPageForHistory(applyUserId, approvalUserId)
                        3 -> getAmibaPurchasePageForHistory(applyUserId, approvalUserId)
                        4 -> getAmibaReimbursePageForHistory(applyUserId, approvalUserId)
                        5 -> getAmibaTemporaryePageForHistory(applyUserId, approvalUserId)
                        6 -> getCompanyPurchasePageForHistory(applyUserId, approvalUserId)
                        7 -> getCompanyPhonePayPageForHistory(applyUserId, approvalUserId)
                    }
                    refreshLayout.finishLoadMore()
                }, 0
            )
        }
        bindingView.refreshLayout.autoRefresh() //第一次进入触发自动刷新，演示效果
    }

    private fun showOffline() {
        bindingView.llStateful.showOffline { bindingView.refreshLayout.autoRefresh() }
        bindingView.refreshLayout.setEnableLoadMore(false)
    }

    private fun showError() {
        bindingView.llStateful.showError { bindingView.refreshLayout.autoRefresh() }
        bindingView.refreshLayout.setEnableLoadMore(false)
    }

    private enum class Status {
        SUCCESS, EMPTY, ERROR, NO_NET
    }

    private fun getRefreshStatus(size: Int): Status {
        return if (size == 0) {
            Status.EMPTY
        } else Status.SUCCESS
    }

    private fun setp(msgBeans: MutableList<MsgHistoryBean>) {
        if (pageNo == 1) {
            when (getRefreshStatus(msgBeans.size)) {
                Status.SUCCESS -> {
                    mAdapter.setList(msgBeans)
                    if (msgBeans.size < pageSize) {
                        bindingView.refreshLayout.setEnableLoadMore(false)
                    } else {
                        bindingView.refreshLayout.setEnableLoadMore(true)
                    }
                    bindingView.refreshLayout.resetNoMoreData() //setNoMoreData(false);
                    bindingView.llStateful.showContent()
                }
                Status.EMPTY -> {
                    bindingView.llStateful.showEmpty()
                    bindingView.refreshLayout.setEnableLoadMore(false)
                }
                Status.ERROR -> showError()
                Status.NO_NET -> showOffline()
            }
            bindingView.refreshLayout.finishRefresh()
        } else {
            if (msgBeans.size == 0) {
                ToastUtils.showShort("数据全部加载完毕")
                bindingView.refreshLayout.finishLoadMoreWithNoMoreData() //将不会再次触发加载更多事件
            } else {
                mAdapter.addData(msgBeans)
                bindingView.refreshLayout.finishLoadMore()
            }
        }
    }

    /**
     * app端阿米巴安装历史申请接口
     */
    private fun getAmibaInstallPageForHistory(applyUserId: Int, approvalUserId: String?) {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()
        viewModel.getAmibaInstallPageForHistory(applyUserId, approvalUserId, pageNo, pageSize)
            .observe(this, object : ObserverState<MutableList<AmibaInstallPageByUserIdBean>>() {
                override fun onDataChange(data: MutableList<AmibaInstallPageByUserIdBean>) {
                    customDialog.dismiss()
                    val msgBeanList = mutableListOf<MsgHistoryBean>()
                    for (bean in data) {
                        msgBeanList.add(
                            MsgHistoryBean(
                                bean.amibaInstallId, bean.createUser, bean.createTime,
                                bean.approvalDate, bean.approvalState
                            )
                        )
                    }
                    setp(msgBeanList)
                    super.onDataChange(data)
                }

                override fun onError(msg: String?, code: Int) {
                    customDialog.dismiss()
                    ToastUtils.showShort(mContext, msg)
                    super.onError(msg, code)
                }
            })

    }


    /**
     * app端阿米巴付款历史申请接口
     */
    private fun getAmibaPayPageForHistory(applyUserId: Int, approvalUserId: String?) {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()

        viewModel.getAmibaPayPageForHistory(applyUserId, approvalUserId, pageNo, pageSize)
            .observe(this, object : ObserverState<MutableList<AmibaProjectListByOrgIdBean>>() {
                override fun onDataChange(data: MutableList<AmibaProjectListByOrgIdBean>) {
                    customDialog.dismiss()
                    val msgBeanList = mutableListOf<MsgHistoryBean>()
                    for (bean in data) {
                        msgBeanList.add(
                            MsgHistoryBean(
                                bean.amibaPayId, bean.createUser, bean.createTime,
                                bean.approvalDate, bean.approvalState
                            )
                        )
                    }
                    setp(msgBeanList)
                    super.onDataChange(data)
                }

                override fun onError(msg: String?, code: Int) {
                    customDialog.dismiss()
                    ToastUtils.showShort(mContext, msg)
                    super.onError(msg, code)
                }
            })
    }

    /**
     * app端阿米巴采购历史申请接口
     */
    private fun getAmibaPurchasePageForHistory(applyUserId: Int, approvalUserId: String?) {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()

        viewModel.getAmibaPurchasePageForHistory(applyUserId, approvalUserId, pageNo, pageSize)
            .observe(this, object : ObserverState<MutableList<SellPurchaseRequistionBean>>() {
                override fun onDataChange(data: MutableList<SellPurchaseRequistionBean>) {
                    customDialog.dismiss()
                    val msgBeanList = mutableListOf<MsgHistoryBean>()
                    for (bean in data) {
                        msgBeanList.add(
                            MsgHistoryBean(
                                bean.amibaPurchaseId, bean.createUser, bean.createTime,
                                bean.approvalDate, bean.approvalState
                            )
                        )
                    }
                    setp(msgBeanList)
                    super.onDataChange(data)
                }

                override fun onError(msg: String?, code: Int) {
                    customDialog.dismiss()
                    ToastUtils.showShort(mContext, msg)
                    super.onError(msg, code)
                }
            })
    }

    /**
     * app端阿米巴报销历史申请接口
     */
    private fun getAmibaReimbursePageForHistory(applyUserId: Int, approvalUserId: String?) {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()
        viewModel.getAmibaReimbursePageForHistory(applyUserId, approvalUserId, pageNo, pageSize)
            .observe(this, object : ObserverState<MutableList<AmibaReimbursePageByUserIdBean>>() {
                override fun onDataChange(data: MutableList<AmibaReimbursePageByUserIdBean>) {
                    customDialog.dismiss()
                    val msgBeanList = mutableListOf<MsgHistoryBean>()
                    for (bean in data) {
                        msgBeanList.add(
                            MsgHistoryBean(
                                bean.amibaReimburseId, bean.createUser, bean.createTime,
                                bean.approvalDate, bean.approvalState
                            )
                        )
                    }
                    setp(msgBeanList)
                    super.onDataChange(data)
                }

                override fun onError(msg: String?, code: Int) {
                    customDialog.dismiss()
                    ToastUtils.showShort(mContext, msg)
                    super.onError(msg, code)
                }
            })
    }

    /**
     * app端阿米巴临时缴费续费历史申请接口
     */
    private fun getAmibaTemporaryePageForHistory(applyUserId: Int, approvalUserId: String?) {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()
        viewModel.getAmibaTemporaryePageForHistory(applyUserId, approvalUserId, pageNo, pageSize)
            .observe(this, object : ObserverState<MutableList<AmibaTemporaryePageByUserIdBean>>() {
                override fun onDataChange(data: MutableList<AmibaTemporaryePageByUserIdBean>) {
                    customDialog.dismiss()
                    val msgBeanList = mutableListOf<MsgHistoryBean>()
                    for (bean in data) {
                        msgBeanList.add(
                            MsgHistoryBean(
                                bean.amibaTemporaryId, bean.createUser, bean.createTime,
                                bean.approvalDate, bean.approvalState
                            )
                        )
                    }
                    setp(msgBeanList)
                    super.onDataChange(data)
                }

                override fun onError(msg: String?, code: Int) {
                    customDialog.dismiss()
                    ToastUtils.showShort(mContext, msg)
                    super.onError(msg, code)
                }
            })
    }

    /**
     * app端公司商务采购历史申请接口
     */
    private fun getCompanyPurchasePageForHistory(applyUserId: Int, approvalUserId: String?) {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()
        viewModel.getCompanyPurchasePageForHistory(applyUserId, approvalUserId, pageNo, pageSize)
            .observe(this, object : ObserverState<MutableList<CompanyPurchaseByUserIdBean>>() {
                override fun onDataChange(data: MutableList<CompanyPurchaseByUserIdBean>) {
                    customDialog.dismiss()
                    val msgBeanList = mutableListOf<MsgHistoryBean>()
                    for (bean in data) {
                        msgBeanList.add(
                            MsgHistoryBean(
                                bean.companyPurchaseId, bean.createUser, bean.createTime,
                                bean.approvalDate, bean.approvalState
                            )
                        )
                    }
                    setp(msgBeanList)
                    super.onDataChange(data)
                }

                override fun onError(msg: String?, code: Int) {
                    customDialog.dismiss()
                    ToastUtils.showShort(mContext, msg)
                    super.onError(msg, code)
                }
            })
    }

    /**
     * app端公司手机号缴费历史申请接口
     */
    private fun getCompanyPhonePayPageForHistory(applyUserId: Int, approvalUserId: String?) {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()
        viewModel.getCompanyPhonePayPageForHistory(applyUserId, approvalUserId, pageNo, pageSize)
            .observe(this, object : ObserverState<MutableList<CompanyPhonePayPageByUserIdBean>>() {
                override fun onDataChange(data: MutableList<CompanyPhonePayPageByUserIdBean>) {
                    customDialog.dismiss()
                    val msgBeanList = mutableListOf<MsgHistoryBean>()
                    for (bean in data) {
                        msgBeanList.add(
                            MsgHistoryBean(
                                bean.companyPhonePayId, bean.createUser, bean.createTime,
                                bean.approvalDate, bean.approvalState
                            )
                        )
                    }
                    setp(msgBeanList)
                    super.onDataChange(data)
                }

                override fun onError(msg: String?, code: Int) {
                    customDialog.dismiss()
                    ToastUtils.showShort(mContext, msg)
                    super.onError(msg, code)
                }
            })

    }

}